package com.imay.photopicker;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.imay.capturefilter.MagicEngine;
import com.imay.capturefilter.R;
import com.imay.capturefilter.camera.CameraEngine;
import com.imay.capturefilter.camera.utils.CameraUtils;
import com.imay.capturefilter.helper.SavePictureTask;
import com.imay.capturefilter.utils.ICUtils;
import com.imay.capturefilter.utils.MagicFilterTools;
import com.imay.capturefilter.widget.MagicCameraView;
import com.imay.photopicker.activity.BaseActivity;
import com.imay.photopicker.manager.CameraManager;

import java.io.File;

/**
 * Created by Administrator on 2017/3/17.
 */

public class CameraActivity extends BaseActivity implements View.OnClickListener {

    private static String SHARED_ELEMENT_NAME = "transitionView";

    private int mFlashMode = 0; //0关，1自动，2开, 3禁用：前置摄像头，

    private MagicEngine mMagicEngine;
    private MagicCameraView mMagicCameraView;
    private ImageView mIvFlash;

    public static final int REQUEST_CODE = 1;
    private Context mContext;

    public static void startActivity(Activity activity, View transitionView, int request) {
        Intent intent = new Intent(activity, CameraActivity.class);
        activity.startActivityForResult(intent, request);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.picker_activity_camera;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mContext = this;

        MagicEngine.Builder builder = new MagicEngine.Builder();
        mMagicCameraView = $(R.id.glsurfaceview_camera);
        mMagicCameraView.setTag("photopicker");
        mMagicEngine = builder.build(mMagicCameraView);

        $(R.id.iv_beauty).setSelected(true);
        CameraManager manager = new CameraManager(this, mMagicCameraView, (ImageView) $(R.id.iv_focus));

        $(R.id.iv_switch_camera).setOnClickListener(this);
        $(R.id.iv_btn_take_photo).setOnClickListener(this);
        $(R.id.iv_btn_sys_photo).setOnClickListener(this);
        $(R.id.iv_beauty).setOnClickListener(this);
        $(R.id.iv_close).setOnClickListener(this);
        mIvFlash = $(R.id.iv_flash);
        $(R.id.iv_flash).setOnClickListener(this);

        /**
         * 设置闪光灯图片
         */
        if (!CameraEngine.getCameraBackStatus()) {
            mIvFlash.setImageResource(R.mipmap.btn_03_camera_flash_clos);
        } else {
            mIvFlash.setImageResource(R.mipmap.btn_03_camera_flash_clos_disable);
        }
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_CANCELED, getIntent());
        super.onBackPressed();
        CameraUtils.release();
        CameraEngine.releaseCamera();
        CameraEngine.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            mMagicCameraView.resumeCamera();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        try {
            mMagicCameraView.pauceCamera();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CameraUtils.release();
        CameraEngine.releaseCamera();
        CameraEngine.onDestroy();
    }

    @Override
    protected boolean useDynamicTitleBar() {
        return false;
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_switch_camera) {
            mMagicCameraView.switchCamera();
            if (!CameraEngine.getCameraBackStatus()) {
                mFlashMode = 3;
            } else {
                mFlashMode = 0;
            }
            setViewFlasMode();
        } else if (id == R.id.iv_btn_take_photo) {
            mMagicEngine.setFlashMode(mFlashMode);
            takePhoto();
        } else if (id == R.id.iv_btn_sys_photo) {
            setResult(RESULT_CANCELED);
            finish();
        } else if (id == R.id.iv_beauty) {
            if (view.isSelected()) {
                mMagicEngine.setFilter(MagicFilterTools.types[1]);
            } else {
                mMagicEngine.setFilter(MagicFilterTools.types[0]);
            }
            view.setSelected(!view.isSelected());
        } else if (id == R.id.iv_close) {
            onBackPressed();
        } else if (id == R.id.iv_flash) {
            setFlashMode();
        }
    }


    private void takePhoto() {
        //findViewById(R.id.iv_btn_capture).setEnabled(false);
        final Dialog dialog = ICUtils.createDialog(this, getString(R.string.IC_img_msg_create));
        dialog.show();
        File imageFile = ICUtils.getOutputMediaFile(CameraActivity.this);
        if (imageFile != null) {
            mMagicEngine.savePicture(imageFile, new SavePictureTask.OnPictureSaveListener() {
                @Override
                public void onSaved(final String result) {
                    dialog.dismiss();
                    MediaScannerConnection.scanFile(mContext,
                            new String[]{result}, null,
                            new MediaScannerConnection.OnScanCompletedListener() {
                                @Override
                                public void onScanCompleted(final String path, final Uri uri) {
                                    // 返回图片路径
                                    getIntent().putExtra("path", result);
                                    setResult(RESULT_OK, getIntent());
                                    finish();
                                }
                            });
                }
            });
        } else {
            dialog.dismiss();
            Toast.makeText(CameraActivity.this, "保存图片失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ClipActivity.CLIP_REQUEST_CODE_2) {
            if (resultCode == RESULT_OK) {
                setResult(RESULT_OK, data);
                finish();
            } else if (resultCode == RESULT_CANCELED) {

            }
        }
    }

    private void setFlashMode() {
        if (mFlashMode > 1) {
            mFlashMode = 0;
        } else {
            mFlashMode = mFlashMode + 1;
        }
        setViewFlasMode();
    }

    private void setViewFlasMode() {
        if (!CameraEngine.getCameraBackStatus()) {//前置摄像头，不可用
            mMagicEngine.setFlashMode(3);
            mIvFlash.setImageResource(R.mipmap.btn_03_camera_flash_clos);
            mIvFlash.setEnabled(false);
            mIvFlash.setImageResource(R.mipmap.btn_03_camera_flash_clos_disable);
        } else {
            mMagicEngine.setFlashMode(mFlashMode);
            mIvFlash.setEnabled(true);
            if (mFlashMode == 1) {
                mIvFlash.setImageResource(R.mipmap.btn_03_camera_flash_auto);
            } else if (mFlashMode == 2) {
                mIvFlash.setImageResource(R.mipmap.btn_03_camera_flash_default);
            } else {
                mIvFlash.setImageResource(R.mipmap.btn_03_camera_flash_clos);
            }
        }
    }
}
